<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>知识库文件上传</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .file-upload-area {
            transition: all 0.3s ease;
        }
        
        .file-upload-area.drag-over {
            border-color: #4f46e5;
            background-color: #f0f9ff;
        }
        
        .file-item {
            animation: fadeIn 0.3s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .progress-bar {
            transition: width 0.3s ease;
        }
        
        .file-icon {
            font-size: 1.5rem;
        }
        
        .file-icon.md { color: #3b82f6; }
        .file-icon.txt { color: #10b981; }
        .file-icon.sql { color: #f59e0b; }
        .file-icon.other { color: #6b7280; }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto max-w-4xl py-8 px-4">
        <!-- 页面标题 -->
        <div class="text-center mb-10">
            <h1 class="text-3xl font-bold text-gray-800">知识库文件上传</h1>
            <p class="text-gray-600 mt-2">上传文档到您的知识库，支持 .md, .txt, .sql 文件类型</p>
        </div>
        
        <!-- 上传表单 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-8">
            <!-- 知识库名称输入 -->
            <div class="mb-6">
                <label for="ragTag" class="block text-sm font-medium text-gray-700 mb-2">知识库名称</label>
                <input 
                    type="text" 
                    id="ragTag" 
                    placeholder="请输入知识库名称" 
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    maxlength="50"
                >
                <p class="text-xs text-gray-500 mt-1">此名称将用于标识您的知识库</p>
            </div>
            
            <!-- 文件上传区域 -->
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">上传文件</label>
                <div 
                    id="fileUploadArea" 
                    class="file-upload-area border-2 border-dashed border-gray-300 rounded-xl p-8 text-center cursor-pointer transition-colors duration-200 hover:border-indigo-400"
                >
                    <div class="flex flex-col items-center justify-center space-y-4">
                        <div class="h-16 w-16 rounded-full bg-indigo-100 flex items-center justify-center">
                            <i class="fas fa-cloud-upload-alt text-indigo-500 text-2xl"></i>
                        </div>
                        <div>
                            <p class="text-lg font-medium text-gray-700">拖放文件到此处或点击上传</p>
                            <p class="text-sm text-gray-500 mt-1">支持 .md, .txt, .sql 文件类型，单个文件不超过 10MB</p>
                        </div>
                        <button id="fileSelectButton" class="bg-indigo-600 text-white px-6 py-2 rounded-lg hover:bg-indigo-700 transition-colors duration-200">
                            选择文件
                        </button>
                    </div>
                    <input 
                        type="file" 
                        id="fileInput" 
                        class="hidden" 
                        multiple 
                        accept=".md,.txt,.sql"
                    >
                </div>
            </div>
            
            <!-- 已选择文件列表 -->
            <div id="fileList" class="space-y-4">
                <!-- 文件项将通过JS动态添加 -->
            </div>
            
            <!-- 上传按钮 -->
            <div class="mt-8 flex justify-end">
                <button 
                    id="uploadButton" 
                    class="bg-indigo-600 text-white px-8 py-3 rounded-lg hover:bg-indigo-700 transition-colors duration-200 flex items-center disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled
                >
                    <i class="fas fa-upload mr-2"></i>
                    <span>上传文件</span>
                </button>
            </div>
        </div>
        
        <!-- 上传结果 -->
        <div id="uploadResult" class="hidden">
            <!-- 上传结果将通过JS动态添加 -->
        </div>
        
        <!-- 使用说明 -->
        <div class="bg-white rounded-xl shadow-md p-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">使用说明</h2>
            <ul class="space-y-3 text-gray-600">
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                    <span>上传的文档将被解析并添加到您的知识库中</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                    <span>支持 Markdown (.md)、纯文本 (.txt) 和 SQL (.sql) 文件</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                    <span>每个文件大小不应超过 10MB</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                    <span>您可以一次选择多个文件进行上传</span>
                </li>
            </ul>
        </div>
    </div>

    <script>
        // 获取DOM元素
        const ragTagInput = document.getElementById('ragTag');
        const fileUploadArea = document.getElementById('fileUploadArea');
        const fileSelectButton = document.getElementById('fileSelectButton');
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        const uploadButton = document.getElementById('uploadButton');
        const uploadResult = document.getElementById('uploadResult');
        
        // 存储选中的文件
        let selectedFiles = [];
        
        // 初始化
        function init() {
            bindEvents();
        }
        
        // 绑定事件
        function bindEvents() {
            // 点击上传区域触发文件选择
            fileUploadArea.addEventListener('click', () => {
                fileInput.click();
            });
            
            // 文件选择按钮
            fileSelectButton.addEventListener('click', (e) => {
                e.stopPropagation();
                fileInput.click();
            });
            
            // 文件选择变化
            fileInput.addEventListener('change', handleFileSelect);
            
            // 拖放功能
            fileUploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                fileUploadArea.classList.add('drag-over');
            });
            
            fileUploadArea.addEventListener('dragleave', () => {
                fileUploadArea.classList.remove('drag-over');
            });
            
            fileUploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                fileUploadArea.classList.remove('drag-over');
                
                if (e.dataTransfer.files.length) {
                    handleFiles(e.dataTransfer.files);
                }
            });
            
            // 上传按钮点击
            uploadButton.addEventListener('click', uploadFiles);
            
            // 知识库名称输入变化
            ragTagInput.addEventListener('input', validateForm);
        }
        
        // 处理文件选择
        function handleFileSelect(e) {
            if (e.target.files.length) {
                handleFiles(e.target.files);
            }
        }
        
        // 处理文件
        function handleFiles(files) {
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 检查文件类型
                if (!isValidFileType(file)) {
                    showMessage(`文件 "${file.name}" 类型不支持，仅支持 .md, .txt, .sql 文件`, 'error');
                    continue;
                }
                
                // 检查文件大小 (10MB)
                if (file.size > 10 * 1024 * 1024) {
                    showMessage(`文件 "${file.name}" 超过 10MB 大小限制`, 'error');
                    continue;
                }
                
                // 检查是否已存在同名文件
                if (selectedFiles.some(f => f.name === file.name)) {
                    showMessage(`文件 "${file.name}" 已存在`, 'warning');
                    continue;
                }
                
                // 添加到选中文件列表
                selectedFiles.push(file);
                
                // 添加到文件列表显示
                addFileToList(file);
            }
            
            // 重置文件输入，允许选择相同文件
            fileInput.value = '';
            
            // 验证表单
            validateForm();
        }
        
        // 检查文件类型是否有效
        function isValidFileType(file) {
            const validExtensions = ['.md', '.txt', '.sql'];
            const fileName = file.name.toLowerCase();
            return validExtensions.some(ext => fileName.endsWith(ext));
        }
        
        // 获取文件类型图标
        function getFileIcon(file) {
            const ext = file.name.split('.').pop().toLowerCase();
            switch (ext) {
                case 'md': return '<i class="fab fa-markdown file-icon md"></i>';
                case 'txt': return '<i class="fas fa-file-alt file-icon txt"></i>';
                case 'sql': return '<i class="fas fa-database file-icon sql"></i>';
                default: return '<i class="fas fa-file file-icon other"></i>';
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 添加文件到列表显示
        function addFileToList(file) {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item bg-gray-50 rounded-lg p-4 flex items-center justify-between';
            fileItem.dataset.fileName = file.name;
            
            fileItem.innerHTML = `
                <div class="flex items-center space-x-4">
                    ${getFileIcon(file)}
                    <div>
                        <p class="font-medium text-gray-800">${file.name}</p>
                        <p class="text-sm text-gray-500">${formatFileSize(file.size)}</p>
                    </div>
                </div>
                <button class="text-red-500 hover:text-red-700 delete-file" data-file-name="${file.name}">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            
            // 绑定删除事件
            const deleteButton = fileItem.querySelector('.delete-file');
            deleteButton.addEventListener('click', (e) => {
                e.stopPropagation();
                removeFile(file.name);
            });
            
            fileList.appendChild(fileItem);
        }
        
        // 移除文件
        function removeFile(fileName) {
            // 从选中文件列表中移除
            selectedFiles = selectedFiles.filter(file => file.name !== fileName);
            
            // 从DOM中移除文件项
            const fileItem = document.querySelector(`.file-item[data-file-name="${fileName}"]`);
            if (fileItem) {
                fileItem.remove();
            }
            
            // 验证表单
            validateForm();
        }
        
        // 验证表单
        function validateForm() {
            const hasRagTag = ragTagInput.value.trim().length > 0;
            const hasFiles = selectedFiles.length > 0;
            
            uploadButton.disabled = !(hasRagTag && hasFiles);
        }
        
        // 上传文件
        function uploadFiles() {
            const ragTag = ragTagInput.value.trim();
            
            if (!ragTag) {
                showMessage('请输入知识库名称', 'error');
                return;
            }
            
            if (selectedFiles.length === 0) {
                showMessage('请选择要上传的文件', 'error');
                return;
            }
            
            // 禁用上传按钮
            uploadButton.disabled = true;
            uploadButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><span>上传中...</span>';
            
            // 创建FormData
            const formData = new FormData();
            formData.append('ragTag', ragTag);
            
            // 添加所有文件
            selectedFiles.forEach(file => {
                formData.append('file', file);
            });
            
            // 发送请求
            fetch('http://localhost:8080/api/rag/file/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('上传失败，服务器返回错误状态');
                }
                return response.json();
            })
            .then(data => {
                if (data.code === '200') {
                    showUploadResult(true, '文件上传成功！');
                    // 清空表单
                    resetForm();
                } else {
                    throw new Error(data.info || '上传失败');
                }
            })
            .catch(error => {
                console.error('上传错误:', error);
                showUploadResult(false, error.message || '上传失败，请稍后重试');
            })
            .finally(() => {
                // 恢复上传按钮
                uploadButton.disabled = false;
                uploadButton.innerHTML = '<i class="fas fa-upload mr-2"></i><span>上传文件</span>';
            });
        }
        
        // 显示上传结果
        function showUploadResult(success, message) {
            uploadResult.className = success ? 'bg-green-50 border border-green-200 rounded-xl p-6 mb-8' : 'bg-red-50 border border-red-200 rounded-xl p-6 mb-8';
            uploadResult.innerHTML = `
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        ${success ? 
                            '<i class="fas fa-check-circle text-green-500 text-xl"></i>' : 
                            '<i class="fas fa-exclamation-circle text-red-500 text-xl"></i>'
                        }
                    </div>
                    <div class="ml-3">
                        <h3 class="${success ? 'text-green-800' : 'text-red-800'} font-medium">
                            ${success ? '上传成功' : '上传失败'}
                        </h3>
                        <div class="${success ? 'text-green-700' : 'text-red-700'} mt-1 text-sm">
                            <p>${message}</p>
                        </div>
                    </div>
                </div>
            `;
            uploadResult.classList.remove('hidden');
            
            // 5秒后自动隐藏结果
            setTimeout(() => {
                uploadResult.classList.add('hidden');
            }, 5000);
        }
        
        // 重置表单
        function resetForm() {
            selectedFiles = [];
            fileList.innerHTML = '';
            ragTagInput.value = '';
            validateForm();
        }
        
        // 显示消息
        function showMessage(message, type) {
            // 创建消息元素
            const messageEl = document.createElement('div');
            messageEl.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
                type === 'error' ? 'bg-red-500 text-white' : 
                type === 'warning' ? 'bg-yellow-500 text-white' : 
                'bg-blue-500 text-white'
            }`;
            messageEl.innerHTML = `
                <div class="flex items-center">
                    <i class="fas ${
                        type === 'error' ? 'fa-exclamation-circle' : 
                        type === 'warning' ? 'fa-exclamation-triangle' : 
                        'fa-info-circle'
                    } mr-2"></i>
                    <span>${message}</span>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(messageEl);
            
            // 3秒后移除
            setTimeout(() => {
                messageEl.remove();
            }, 3000);
        }
        
        // 初始化应用
        init();
    </script>
</body>
</html>